import { defineStore } from 'pinia'
import axios from 'axios'
import { useStaffStore } from './useStaffStore'
import { ElMessage } from 'element-plus'
import { emitter } from '@/utils/emitter'
import instance from '@/api'
interface serviceLocationType{
  lat:string,
  lng:string
}
interface serviceHumanType{
  id:number,
  name:string,                                        
  distance:string
}
//服务人员
export const useStaffSelectStore = defineStore('staffSelect', {
  state(){
    return{
      dialogTableVisible: false,//控制选择阿姨弹窗的显示与隐藏
      resultLocation : {lat: 34.90469, lng: 113.40717},  //单个员工位置经纬度
      customLocation:{lat: 34.90469, lng: 113.40717}, //顾客位置经纬度
      mapDetail: false, // 控制地图详情弹窗的显示，
      gridData: [] as any[], // 控制地图详情弹窗的显示，
      location: [] as any[], // 员工列表随机生成的经纬度,
      rowInfo: {} as any,
      checkBox: [] as any[],
      myTable: null as any
    }
  },
  actions: {
    // 重置所有状态
    resetAllState() {
      this.gridData = []
      this.location = []
      this.checkBox = []
      this.rowInfo = {}
      this.myTable = null
      this.dialogTableVisible = false
    },
    //打开距离详情
    distanceDetail(index:number){
      this.mapDetail = true
      this.resultLocation = this.location[index]
    },
    // 打开选择阿姨弹窗
    async selectHuman(row: any){
      // 先重置所有状态
      this.resetAllState()
      this.dialogTableVisible = true
      
      const staffStore = useStaffStore()
      await staffStore.fetchStaffList()
      this.gridData.push(...staffStore.availableStaffList)
      this.rowInfo = row
      const customAddress = row.address
      
      // 为每个阿姨生成新的位置
      for(let i = 0; i < this.gridData.length; i++){
        this.location.push(this.createLocation())
      }
      
      // 计算距离
      this.distanceCalculate(customAddress, this.location)
    },
    //生成员工的随机地址
    createLocation(){
      //郑州范围内生成经纬度
      const lat = (Math.random() * (34.90 - 34.70) + 34.70).toFixed(6)
      const lng = (Math.random() * (113.80 - 113.50) + 113.50).toFixed(6);
      const location = {
        lat,
        lng
      }
      return location
    },
    async distanceCalculate(customAddress:string,serviceLocation:Array<serviceLocationType>){
      //地址解析
      const resp = await axios.get('http://localhost:3000/api/geocoder',{ params:{ address:customAddress } })
      Object.assign(this.customLocation, resp.data.result.location)
      let from = ''
      if (Array.isArray(serviceLocation)) {
        serviceLocation.forEach(item => {
          from += `${item.lat},${item.lng};`
        })
      }
      const res = from.slice(0, -1)
      const to = `${this.customLocation.lat},${this.customLocation.lng}`
      const serviceLocResp = await axios.get('http://localhost:3000/api/distance',{
        params:{
          from: res,
          to,
        }
      })
      const { status } = serviceLocResp.data
      if(status === 120){
        ElMessage.error('请求频繁, 请稍后再试')
        return;
      } 
      const { rows } = serviceLocResp.data.result
      for(let i = 0; i < this.gridData.length; i++){
        this.gridData[i].distance = (rows[i].elements[0].distance)/100 + 'km'
      }
    },
    async confirmServiceHuman(){
      const staffIds: any[] = []
      this.checkBox.forEach((item: any) => {
        staffIds.push(item.id)
      })
      const { id, arrivalTime, payStatus } = this.rowInfo
      const send = {
        time: arrivalTime,
        staff:staffIds,
        payStatus: payStatus
      }
      const res = await instance.put(`/api/order/upDateOrder/${id}`, send)
      const { status } = res
      if(status === 200){
        // 更新rowInfo中的serviceStaff
        this.rowInfo.serviceStaff = res.data.serviceStaff
        // 触发更新事件
        emitter.emit('updateServiceStaff', {
          orderId: id,
          serviceStaff: res.data.serviceStaff
        })
        ElMessage.success('分配成功')
        if(arrivalTime) emitter.emit('upDateTab')
      } 
      else ElMessage.error('分配失败')
      this.dialogTableVisible = false
      this.myTable?.clearSelection();
    },
    handleSelectionChange(row: serviceHumanType){
      this.checkBox = row
    },
    setLocation(value: Object) {
      this.resultLocation = value
    },
    setCustomLocation(value:Object){
      this.customLocation = value
    },
    setGridData(value:Object){
      this.gridData = value
    },
    setLocationList(value:Object){
      this.location = value
    },
    // 关闭地图弹窗
    closeMapDetail() {
      this.mapDetail = false
    }
  },
})